#include "stdio_impl.h"
#include <nxos.h>

struct iovec {
    void      *iov_base;      /* starting address of buffer */
    size_t    iov_len;        /* size of buffer */
};

static ssize_t __readv(int fd, struct iovec * vec, size_t nr)
{
    ssize_t len;
    int i;

    len = 0;
    for (i = 0; i < nr; i++)
    {
        if (vec[i].iov_base && vec[i].iov_len > 0)
        {
            ssize_t err = NX_FileRead(fd, vec[i].iov_base, vec[i].iov_len);
            len += err;
            if (!err)
            {
                return len;
            }
        }
    }
    return len;
}

size_t __stdio_read(FILE *f, unsigned char *buf, size_t len)
{
	struct iovec iov[2] = {
		{ .iov_base = buf, .iov_len = len - !!f->buf_size },
		{ .iov_base = f->buf, .iov_len = f->buf_size }
	};
	ssize_t cnt;

	cnt = iov[0].iov_len ? __readv(f->fd, iov, 2)
		: NX_FileRead(f->fd, iov[1].iov_base, iov[1].iov_len);
	if (cnt <= 0) {
		f->flags |= cnt ? F_ERR : F_EOF;
		return 0;
	}
	if (cnt <= iov[0].iov_len) return cnt;
	cnt -= iov[0].iov_len;
	f->rpos = f->buf;
	f->rend = f->buf + cnt;
	if (f->buf_size) buf[len-1] = *f->rpos++;
	return len;
}
